<?php

require(BASE_PATH . "include/classes/Auth.php");

class Auth_Mysql extends Auth
{
	private $_query = null;
	
	protected function getDatabase()
	{
		return Mysql::getInstance();
	}
	
	/**
	 * Fetches the user id from the db.
	 */
	protected function fetchUser($userId)
	{
		$this->_mysqlSelectUserById($userId);
		
		return mysql_fetch_assoc($this->_query);
	}
	
	/**
	 * Fetches the userExists(user id) from the db.
	 */
	protected function fetchExistingUser()
	{
		return mysql_fetch_assoc($this->_query);
	}
	
	/**
	 * Fetches the groups where to the user id.
	 */
	protected function fetchGroups($userId)
	{
		$groups = array();
		
		$sql = <<<END
			SELECT * 
			FROM user_groups AS u 
				JOIN groups AS g ON g.id = u.group_id
			WHERE u.user_id = '{$userId}'
END;
		$query = $this->_db->query($sql);
		while($row = mysql_fetch_assoc($query))
		{
			$groups[$row['id']] = $row;
		}
		
		return $groups;
	}
	
	/**
	 * Checks if the user exists.
	 */
	protected function userExists($userId)
	{
		$this->_mysqlSelectUserById($userId);
		
		return (mysql_num_rows($this->_query) == 1);
	}
	
	private function _mysqlSelectUserById($userId)
	{
		$sql = <<<END
			SELECT u.*, i.*
			FROM users AS u
				JOIN user_info AS i ON u.id = i.user_id
			WHERE u.id = {$userId}
END;
		$this->_query = $this->_db->query($sql);
	}
}

?>